import { useCreation, useMount } from "ahooks";
import { Text, View } from "@tarojs/components";

import Moment from "./Moment";
import ByTag from "../ui/ByTag";
import ByText from "../ui/ByText";
import BySpace from "../ui/BySpace";
import ByStepsItem from "../ui/ByStepsItem";

import useAppStore from "@/store";
import useEnum from "@/hooks/useEnum";
import { formatTimeElapsed } from "@/utils";

import { TaskDetail, TaskStep } from "@/types/global";

const tagProps = {
  variant: "outline",
  size: "small",
  rounded: false
} as const;

// 审批状态
const approveStateOptions = [
  {
    label: "审核中",
    color: "primary",
    value: 0,
  },
  {
    label: "已通过",
    color: "success",
    value: 1,
  },
  {
    label: "驳回",
    color: "error",
    value: 2,
  },
  {
    label: "已过期",
    color: "info",
    value: 3,
  },
  {
    label: "自动审批通过",
    color: "success",
    value: 99,
  },
];

const Item = ({
  source,
  onChangeStatus,
}: {
  source: TaskStep;
  onChangeStatus?: (workItemId: number, node: TaskStep) => void;
}) => {
  const userInfo = useAppStore((state) => state.userInfo);
  const { isCurrentStep, state, approvers, startTime, endTime } = source;

  const { getOption } = useEnum(approveStateOptions);

  const viewData = useCreation(() => {
    // 该节点已处理
    const hadApproved = state > 0;

    // 该节点是否自动跳过（不需要该节点审批）
    const isJump = state === 99;

    // 若该节点已处理，找到处理人
    const approver =
      !isJump && hadApproved ? approvers.find((e) => e.state > 0) : undefined;

    return {
      approver,
      state: isJump ? 99 : approver?.state,
      showApproverList: isJump ? [] : approver ? [approver] : approvers,
      dateText: approver && [1, 2].includes(approver.state) ? endTime : "",
    };
  }, []);

  useMount(() => {
    // 该节点登录账号是否可审核: @return 当前审核人Item
    const approvalableUser = isCurrentStep
      ? approvers.find((e) => e.actorId == userInfo?.user_id)
      : undefined;

    // 当存在可以由当前用户审核的节点时，向父级报告（目前数据上没有直接数据判断）
    approvalableUser && onChangeStatus?.(approvalableUser.workItemId, source);
  });

  // const showStatus = isCurrentStep || state > 0;
  const enumConfig = getOption(isCurrentStep ? 0 : viewData.state);

  const dateText = isCurrentStep ? (
    "已等待" + formatTimeElapsed(startTime)
  ) : (
    <Moment value={viewData?.dateText} type="full" />
  );

  return (
    <ByStepsItem
      title={source.nodeName}
      date={dateText}
      slotStatus={
        !!enumConfig && (
          <ByTag variant="filled" type={enumConfig?.color} size="small">
            {enumConfig?.label}
          </ByTag>
        )
      }
    >
      <BySpace>
        {viewData.showApproverList.map((item) => (
          <ByTag key={item.workItemId} {...tagProps}>
            {item.actorName}
          </ByTag>
        ))}
      </BySpace>

      {viewData.approver?.comment && (
        <View className="mt-3 text-sm">
          <Text className="text-third">审批意见：</Text>
          <ByText type={viewData.approver.state == 2 ? "error" : undefined}>
            {viewData.approver?.comment}
          </ByText>
        </View>
      )}
    </ByStepsItem>
  );
};

export default ({
  source,
  showTitle,
  onChangeStatus,
}: {
  source: TaskDetail;
  showTitle?: boolean;
  onChangeStatus?: (workItemId: number, node: TaskStep) => void;
}) => {
  const { startTime, createUserName, steps } = source;

  return (
    <>
      {showTitle && (
        <View className="mb-3">
          <ByText size="sm" type="third">
            审批流程
          </ByText>
        </View>
      )}

      <ByStepsItem
        title="发起人"
        date={<Moment value={startTime} type="full" />}
        slotStatus={
          <ByTag variant="filled" size="small" type="success">
            已发起
          </ByTag>
        }
      >
        <ByTag {...tagProps}>{createUserName}</ByTag>
      </ByStepsItem>

      {steps.map((item) => (
        <Item
          source={item}
          key={item.nodeId + "_" + item.state}
          onChangeStatus={onChangeStatus}
        />
      ))}
    </>
  );
};
